/*
 * 否词过滤
 * @Author: along
 * @Date: 2019-12-18 19:42:00
 */
<template>
    <div class="container kewordFilter">
        <!-- header -->
        <div class="headerBox">
            <div class="header-left">
                <div class="header-box">
                    <p class="header-box-title">否词:</p>
                    <el-input
                        v-model="header.title"
                        placeholder="请输入否词"
                        suffix-icon="el-icon-search"
                        size="small"
                        clearable
                        @change="getTableData(1)"
                        @keyup.native.enter="getTableData(1)"
                    />
                </div>
                <div class="header-box">
                    <p class="header-box-title">否词状态:</p>
                    <el-select
                        v-model="header.status"
                        filterable
                        placeholder="请选择"
                        size="small"
                        @change="getTableData(1)"
                        clearable
                    >
                        <el-option
                            v-for="item in statusList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </div>
            </div>
            <div class="header-right">
                <div class="header-box">
                    <div class="btn-import-wrap">
                        <input
                            class="import-input"
                            accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                            type="file"
                            @change="fnImportWord($event)">
                        <el-button
                            size="small"
                            class="el-button-input"
                            type="primary">导入否词</el-button>
                    </div>
                    <el-button
                        type="primary"
                        size="small"
                        class="el-button-right"
                        @click="fnExportword()"
                    >下载demo</el-button>
                    <el-button
                        type="primary"
                        size="small"
                        @click="fnAddWord()"
                    >新建否词</el-button>
                </div>
            </div>
        </div>
        <!-- /header -->

        <!-- table -->
        <el-table
            :data="tableData"
            height="100%"
            style="width: 100%;"
            border
            ref="kewordFilter"
            @select="fnSelect"
            @select-all="fnSelectAllTop"
            @selection-change="handleSelectionChange"
        >
            <el-table-column
                type="selection"
                width="40"
                fixed="left"
            />
            <el-table-column
                type="index"
                width="80"
                label="序号"
            />
            <el-table-column
                prop="word"
                label="否词"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="from_price"
                label="价格区间"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            >
                <template slot-scope="scope">
                    <!-- <span >{{ scope.row | setPrice }}</span> -->
                    <span >{{ scope.row.from_price !== '0.00' ? scope.row.from_price : '0' }}-{{ scope.row.to_price !== '0.00' ? scope.row.to_price : '' }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="from_sale"
                label="销量范围"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            >
                <template slot-scope="scope">
                    <span >{{ scope.row.from_sale }} - {{ scope.row.to_sale ? scope.row.to_sale : '' }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="delete_num"
                label="累计清除商品数"
                show-overflow-tooltip
            />
            <el-table-column
                prop="create_time"
                label="加入时间"
                :formatter="emptyFormatter"
            >
                <template slot-scope="scope">
                    <template v-if="scope.row.create_time">{{ scope.row.create_time*1000 | dateFormatter('yyyy/MM/dd HH:mm') }}</template>
                    <template v-else>--</template>
                </template>
            </el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                :formatter="emptyFormatter"
            >
                <template slot-scope="scope">
                    <span v-if="scope.row.status == 1">运行中</span>
                    <span v-if="scope.row.status == 0">已禁用</span>
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                :width="150"
                fixed="right"
            >
                <template slot-scope="scope">
                    <div class="el-button-right">
                        <el-button
                            type="text"
                            class="curse-add"
                            @click="fnStopWord(scope.row)"
                            style="padding: 5px 0;padding:0"
                        >
                            <span v-if="scope.row.status == 1">禁用</span>
                            <span v-if="scope.row.status == 0">运行</span>
                        </el-button>
                        <el-button
                            type="text"
                            class="curse-add"
                            @click="fnDeleteWord(scope.row)"
                            style="padding: 5px 0;marginLeft:0"
                        >
                            删除
                        </el-button>
                        <el-button
                            type="text"
                            class="curse-add"
                            @click="fnEditWord(scope.row)"
                            style="padding: 5px 0;marginLeft:0"
                        >
                            设定价格区间
                        </el-button>
                        <el-button
                            type="text"
                            class="curse-add"
                            @click="fnSetvolum(scope.row)"
                            style="padding: 5px 0;marginLeft:0"
                        >
                            设定销量范围
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- /table -->

        <!-- 新建否词 -->
        <el-dialog
            :title="title"
            :visible.sync="dialogVisible"
            width="510px"
            :close-on-click-modal="false"
        >
            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm"
            >
                <el-form-item
                    label="否词"
                    prop="word"
                    v-if=" id == '' "
                >
                    <el-input
                        v-model="ruleForm.word"
                        placeholder="请输入否词"
                        size="small"
                    />
                </el-form-item>
                <el-form-item
                    label="商品价格"
                    v-if=" id !== '' "
                >
                    <el-input
                        v-model="ruleForm.from_price"
                        size="small"
                        placeholder="请输入起始价"
                        style="width:140px"
                        type="number"
                        min=0
                    />
                    -
                    <el-input
                        v-model="ruleForm.to_price"
                        placeholder="请输入结束价"
                        size="small"
                        style="width:140px"
                        type="number"
                        min=0
                    />
                </el-form-item>
                <!-- <el-form-item
                    label="商品销量"
                >
                    <el-input
                        v-model="ruleForm.from_sale"
                        size="small"
                        placeholder="请输入开始销量"
                        style="width:140px"
                        type="number"
                        min=0
                    />
                    -
                    <el-input
                        v-model="ruleForm.to_sale"
                        placeholder="请输入结束销量"
                        size="small"
                        style="width:140px"
                        type="number"
                        min=0
                    />
                </el-form-item> -->
            </el-form>
            <span
                slot="footer"
                class="dialog-footer">
                <el-button
                    @click="dialogVisible = false"
                    size="small"
                >取 消</el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="fnConfrimWord('ruleForm')">确 定</el-button>
            </span>
        </el-dialog>
        <!-- /新建否词 -->

        <!-- 设定销量范围 -->
        <el-dialog
            title="设定销量范围"
            :visible.sync="dialogVisibleXl"
            width="510px"
            :close-on-click-modal="false"
        >
            <el-form
                ref="ruleFormXl"
                label-width="100px"
                class="demo-ruleForm"
                :model="ruleFormXl"
            >
                <el-form-item
                    label="开始销量"
                >
                    <el-input
                        v-model="ruleFormXl.start_volum"
                        size="small"
                        placeholder="请输入开始销量"
                    />
                </el-form-item>
                <el-form-item
                    label="结束销量"
                >
                    <el-input
                        v-model="ruleFormXl.end_volum"
                        placeholder="请输入结束销量"
                        size="small"
                    />
                </el-form-item>
            </el-form>
            <span
                slot="footer"
                class="dialog-footer">
                <el-button
                    @click="dialogVisibleXl = false"
                    size="small"
                >取 消</el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="fnConfrimXl('ruleFormXl')">确 定</el-button>
            </span>
        </el-dialog>
        <!-- /设定销量范围 -->

        <!-- /分页 -->
        <div class="pagination-wrapper clearfix">
            <el-checkbox
                v-model="checkedAll"
                :indeterminate="checkIndeterminate"
                @change="fnChangeChecked"
            >全选</el-checkbox>
            <el-button
                type="text"
                @click="fnStartword()"
                :disabled="multipleSelection.length == 0 ? true : false"
            >批量运行否词</el-button>
            <el-button
                type="text"
                @click="fnProhibitWord()"
                :disabled="multipleSelection.length == 0 ? true : false"
            >批量禁用否词</el-button>
            <el-pagination
                background
                layout="total, prev, pager, next"
                :current-page.sync="page.now_page"
                :total="page.total_count"
                :page-size="page.page_size"
                @current-change="getTableData"
            />
        </div>
    </div>
</template>

<script>
export default {
    /**
     * @param  {Object}    authResult           //表单权限
     * @param  {Array}     tableData            //表单数据
     * @param  {Object}    page                 //表单分页
     * @param  {Object}    header               //表单检索字段
     * @param  {Array}     statusList           //否词状态
     * @param  {String}    pathName             //记录上一页路由name
     * @param  {Boolean}   checkedAll               //是否全选
     * @param  {Boolean}   multipleSelection        //选择数据
     * @param  {Boolean}   checkIndeterminate       //选中状态
     */
    data () {
        return {
            ruleFormXl: {
                start_volum: '',
                end_volum: ''
            },
            dialogVisibleXl: false,
            title: '新建否词',
            id: '',
            typeModel: '',
            indexSucess: 0,
            indexError: 0,
            checkIndeterminate: false,
            multipleSelection: [],
            checkedAll: false,
            rules: {
                word: [
                    { required: true, message: '请填写否词,不可以为空', trigger: 'blur' }
                ]
            },
            ruleForm: {
                word: '',
                from_price: '',
                to_price: '',
                from_sale: '',
                to_sale: ''
            },
            dialogVisible: false,
            statusList: [{
                value: '',
                label: '全部'
            },{
                value: 1,
                label: '运行中'
            },{
                value: 0,
                label: '已禁用'
            }],
            header: {
                status: '',
                title: ''
            },
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },
            pathName: '',
            tableData: [],
            authResult: {}
        };
    },
    filters: {
        setPrice (val) {
            if (val.from_price && val.to_price) {
                return val.from_price + '-' + val.to_price;
            }

            if (!val.from_price && !val.to_price) {
                return '--';
            }

            if (val.from_price && !val.to_price) {
                return val.from_price + '-';
            }

            if (!val.from_price && val.to_price) {
                return '0-' + val.to_price;
            }
        }
    },
    computed: {},
    watch: {
        dialogVisible (val) {
            if (!val) {
                this.ruleForm = {
                    word: '',
                    from_price: '',
                    to_price: ''
                };
                this.$refs['ruleForm'].resetFields();
            }
        },
        dialogVisibleXl (val) {
            if (!val) {
                this.ruleFormXl = {
                    start_volum: '',
                    end_volum: ''
                };
            }
        }
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            vm.pathName = from.name;
        });
    },
    mounted () {
        this.authResult = this.$route.meta.authResult;
        this.fnBreadcrumb();
        this.getTableData();
        this.fnRecord();
    },
    destroyed(){
        window.removeEventListener('popstate', this.fnGoBack, false);
    },
    methods: {
        /**
         * 设置表单header
         */
        fnBreadcrumb () {
            this.$store.commit('SET_HEADER', [{ title: "APP后台"},{title: '否词过滤'}]);
        },

        /**
         * 获取表格数据
         */
        getTableData (page) {
            this.$post('/student/shop_goods_ignore_word%5Cget_list', {
                page_id: page || this.page.now_page,
                keyword: this.header.title,
                status: this.header.status
            }, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                    this.page.now_page = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                }
            });
        },

        /**
         * 记录上一页路由,监听页面返回并重定向
         */
        fnRecord () {
            this.fnParamUrl();
            if (window.history && window.history.pushState) {
                history.pushState(null, null, document.URL);
                window.addEventListener('popstate', this.fnGoBack, false);
            }
        },

        /**
         * 上一页重定向
         */
        fnGoBack  () {
            this.$router.replace({ name: this.pathName });
        },

        /**
         * 获取路由参数
         */
        fnParamUrl () {
            let query = this.$route.query;
        },

        /**
         * 导入否词
         */
        fnImportWord () {
            let file = event.target.files[0];
            let form = new FormData();

            form.append("file", file);
            this.$post('/student/shop_goods_ignore_word%5Cimport', form, resp => {
                event.target.value = null;
                if (resp.code == 1) {
                    this.getTableData();
                    this.$message({
                        type: 'success',
                        message: '导入成功' || resp.msg,
                        center: true
                    });
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },

        /**
         * 下载demo
         */
        fnExportword () {
            let base = this.$baseUrl;
            let ticket = localStorage.getItem('sessionTicket');
            let url = `${base}/student/shop_goods_ignore_word%5Ccsv?&__ticket=${ticket}`;

            window.open(url);
        },

        /**
         * 设定销量范围
         */
        fnSetvolum (row) {
            this.id = row.id;
            this.ruleFormXl = {
                start_volum: row.from_sale,
                end_volum: row.to_sale
            };
            this.dialogVisibleXl = !this.dialogVisibleXl;
        },

        /**
         * 确定设定销量范围
         */
        fnConfrimXl (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$post('/student/shop_goods_ignore_word%5Cmodify',{
                        id: this.id,
                        from_sale: this.ruleFormXl.start_volum,
                        to_sale: this.ruleFormXl.end_volum
                    },resp=>{
                        if (resp.code == 1) {
                            this.getTableData();
                            this.dialogVisibleXl = !this.dialogVisibleXl;
                            this.$message({
                                type: 'success',
                                message: '设置成功',
                                center: true
                            });
                        } else {
                            this.$message({
                                type: 'waring',
                                message: resp.msg,
                                center: true
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        /**
         * 新建否词
         */
        fnAddWord () {
            this.title = '新建否词';
            this.typeModel = 'add';
            this.id = '';
            this.dialogVisible = !this.dialogVisible;
        },

        /**
         * 设定价格区间
         */
        fnEditWord (row) {
            this.title = '设定价格区间';
            this.typeModel = 'edit';
            this.id = row.id;
            this.ruleForm.from_price = row.from_price;
            this.ruleForm.to_price = row.to_price;
            this.dialogVisible = !this.dialogVisible;
        },

        /**
         * 确定新建否词
         */
        fnConfrimWord (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.typeModel == 'add') {
                        this.$post('/student/shop_goods_ignore_word%5Ccreate',{
                            word: this.ruleForm.word,
                            from_price: this.ruleForm.from_price,
                            to_price: this.ruleForm.to_price,
                            from_sale: this.ruleForm.from_sale,
                            to_sale: this.ruleForm.to_sale
                        },resp=>{
                            if (resp.code == 1) {
                                this.getTableData();
                                this.dialogVisible = !this.dialogVisible;
                                this.$message({
                                    type: 'success',
                                    message: '新建成功',
                                    center: true
                                });
                            } else {
                                this.$message({
                                    type: 'waring',
                                    message: resp.msg,
                                    center: true
                                });
                            }
                        });
                    } else if (this.typeModel == 'edit') {
                        this.$post('/student/shop_goods_ignore_word%5Cmodify',{
                            id: this.id,
                            from_price: this.ruleForm.from_price,
                            to_price: this.ruleForm.to_price ? this.ruleForm.to_price : 0
                        },resp=>{
                            if (resp.code == 1) {
                                this.getTableData();
                                this.dialogVisible = !this.dialogVisible;
                                this.$message({
                                    type: 'success',
                                    message: '更新成功',
                                    center: true
                                });
                            } else {
                                this.$message({
                                    type: 'waring',
                                    message: resp.msg,
                                    center: true
                                });
                            }
                        });
                    } else {
                        return;
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        /**
         * 禁用/运行
         */
        fnStopWord (row) {
            this.$post('/student/shop_goods_ignore_word%5Cset_status',{
                ids: row.id,
                status: row.status == 1 ? 0 : 1
            },resp=>{
                if (resp.code == 1) {
                    this.getTableData();
                    this.$message({
                        type: 'success',
                        message: '设置成功',
                        center: true
                    });
                } else {
                    this.$message({
                        type: 'waring',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },

        /**
         * 批量运行否词
         */
        fnStartword () {
            let ids = [];

            this.$confirm('是否确定选中的否词运行？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.multipleSelection.map(item=>{
                    if (item.status !== 1) {
                        ids.push(item.id);
                    }
                });
                this.$post('/student/shop_goods_ignore_word%5Cset_status',{
                    ids: ids.join(),
                    status: 1
                },resp=>{
                    if (resp.code == 1) {
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '运行成功',
                            center: true
                        });
                    } else {
                        this.$message({
                            type: 'waring',
                            message: resp.msg,
                            center: true
                        });
                    }
                });
            });
        },

        /**
         * 批量禁止否词
         */
        fnProhibitWord () {
            let ids = [];

            this.$confirm('是否确定选中的否词运行？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.multipleSelection.map(item=>{
                    if (item.status !== 0) {
                        ids.push(item.id);
                    }
                });
                this.$post('/student/shop_goods_ignore_word%5Cset_status',{
                    ids: ids.join(),
                    status: 0
                },resp=>{
                    if (resp.code == 1) {
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '禁用成功',
                            center: true
                        });
                    } else {
                        this.$message({
                            type: 'waring',
                            message: resp.msg,
                            center: true
                        });
                    }
                });
            });
        },

        /**
         * 删除
         */
        fnDeleteWord (row) {
            this.$confirm('此操作将永久删除该否词, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/shop_goods_ignore_word%5Cdelete',{
                    id: row.id
                },resp=>{
                    if (resp.code == 1) {
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '删除成功',
                            center: true
                        });
                    } else {
                        this.$message({
                            type: 'waring',
                            message: resp.msg,
                            center: true
                        });
                    }
                });
            });
        },

        /**
         * 选择Checkbox
         */
        fnSelect(selection) {
            if(selection.length == this.tableData.length) {
                this.checkedAll = true;
            }else{
                this.checkedAll = false;
            }
            if(selection.length > 0 && selection.length < this.tableData.length) {
                this.checkIndeterminate = true;
            }else{
                this.checkIndeterminate = false;
            }
        },
        fnSelectAllTop(selection) {
            if(selection.length > 0) {
                this.checkedAll = true;
            }else{
                this.checkedAll = false;
            }
            if(selection.length > 0 && selection.length < this.tableData.length) {
                this.checkIndeterminate = true;
            }else{
                this.checkIndeterminate = false;
            }
        },
        fnChangeChecked() {
            if(this.checkedAll){
                this.toggleSelection(1);
            }else{
                this.toggleSelection();
            }
        },
        toggleSelection(rows) {
            if (rows) {
                this.$refs.kewordFilter.toggleAllSelection();
            } else {
                this.$refs.kewordFilter.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        /**
         * 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) return '--';
            return val;
        }
    }
};
</script>

<style lang="less" scoped>
    .container {
        background-color: #fff;
        padding: 10px 15px 5px 15px;
        display: flex;
        flex-direction: column;
        position: relative;
        width: 100%;
        .headerBox {
            position: relative;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: space-between;
            .header-left, .header-right {
                display: flex;
                align-items: center;
            }
            .header-box {
                display: flex;
                margin-right: 15px;
                align-items: center;
                color: #606266;
                margin-bottom: 10px;
                &-title {
                    margin-right: 2px;
                    white-space: nowrap;
                }
            }
        }
        /* 表单 */
        .scope-price {
            width: 50px;
            height: 50px;
        }
        /* 字体高亮 */
        .cursor-font {
            color: rgb(64, 158, 255);
            cursor: pointer;
        }
        /* 分页 */
        .pagination-wrapper {
            padding-top: 10px;
            padding-bottom: 10px;
            .el-pagination {
                float: right;
                padding: 0;
                background-color: transparent;
            }
        }
    }
    /* 排序 */
    .sort-wrap {
        display: flex;
        align-items: center;
        cursor: pointer;
        .sort-spliter {
            width: 1px;
            height: 12px;
            background: rgba(235, 235, 235, 1);
            margin: 0 10px;
            }
            .btn-sort {
            font-size: 14px;
            line-height: 1;
            color: #ccc;
            &:hover {
                color: #20a0ff;
            }
        }
    }
    .el-button-left {
        margin-left: 40px;
    }
    .el-button-right {
        margin-right: 10px;
    }
    .el-button-input {
        margin-right: 20px;
    }
    .btn-import-wrap {
        margin-left: 15px;
        display: inline-block;
        position: relative;
        overflow: hidden;
        cursor: pointer;
        vertical-align: top;
        .import-input {
            margin-left: -100%;
            position: absolute;
            left: 0;
            top: 0;
            width: 200%;
            height: 100%;
            cursor: pointer;
            opacity: 0;
        }
    }
    .el-button-right {
        display: flex;
        flex-direction: column;
    }
</style>
<style lang="less">
    .kewordFilter .el-table__body-wrapper .el-table__body .el-table__row td {
        border-right: none;
    }
    .kewordFilter .el-table__header-wrapper .el-table__header .has-gutter tr th {
        border-right: none;
    }
    .kewordFilter .el-table .el-table_1_column_6  .cell {
        position: relative;
    }
    .kewordFilter .el-range-editor--small .el-range-separator{
        padding: 0 1px !important;
    }
</style>
